package com.core.life.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.core.common.pageModel.Combo;
import com.core.common.pageModel.EasyuiDataGridColumns;
import com.core.life.dao.IAccountingRelationsDao;
import com.core.life.entity.AccountingRelationsEntity;
import com.core.life.entity.ConsumeRecordEntity;
import com.core.life.service.IAccountingRelationsService;
import com.core.sys.service.IUserService;
import com.core.sys.vo.UserVo;
import com.utils.date.DateUtil;

@Service
public class AccountingRelationsServiceImpl implements IAccountingRelationsService{

	@Resource
	private IAccountingRelationsDao accountingRelationsDao;
	@Resource
	private IUserService userService;
	
	@Transactional
	@Override
	public void saveAccountingRelations(ConsumeRecordEntity consumeRecord, String strConsumeUserIds) {
	    String[] userIds = strConsumeUserIds.split(",");
        String[] consumeUserIdArray = new String[userIds.length];
        Float[] consumeArray = new Float[userIds.length];
        Float consumeMoney = 0f;
        for (int i = 0; i < userIds.length; i++) {
            String[]consumeUsers = userIds[i].split("/");
            consumeUserIdArray[i] = consumeUsers[0];
            consumeArray[i] = Float.parseFloat(consumeUsers[1]);
            consumeMoney += consumeArray[i];
        }
        if(consumeMoney == 0){
            String[] consumeUserIds = consumeRecord.getConsumeUserIds().split(",");
            //平均消费金额
            float averageConsumeMoney = consumeRecord.getConsumeMoney() / consumeUserIds.length;
            BigDecimal b = new BigDecimal(averageConsumeMoney);  
            averageConsumeMoney = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
            AccountingRelationsEntity ar = null;
            for (String consumeUserId : consumeUserIds) {
                ar = new AccountingRelationsEntity();
                ar.setConsumeRecordId(consumeRecord.getId());
                ar.setTargetUserId(consumeRecord.getPayerUserId());
                ar.setSourceUserId(Long.parseLong(consumeUserId));
                ar.setPayMoney(averageConsumeMoney);
                ar.setDay(consumeRecord.getDay());
                ar.setMonth(consumeRecord.getMonth());
                ar.setYear(consumeRecord.getYear());
                accountingRelationsDao.save(ar);
            }
        }else{
            AccountingRelationsEntity ar = null;
            for (int i = 0; i < consumeUserIdArray.length; i++) {
                ar = new AccountingRelationsEntity();
                ar.setConsumeRecordId(consumeRecord.getId());
                ar.setTargetUserId(consumeRecord.getPayerUserId());
                ar.setSourceUserId(Long.parseLong(consumeUserIdArray[i]));
                ar.setPayMoney(consumeArray[i]);
                ar.setDay(consumeRecord.getDay());
                ar.setMonth(consumeRecord.getMonth());
                ar.setYear(consumeRecord.getYear());
                accountingRelationsDao.save(ar);
            }
        }
	}

	@Transactional
	@Override
	public void updateAccountingRelations(ConsumeRecordEntity consumeRecord, String strConsumeUserIds) {
		//先删除，再保存
		List<Long> ids = new ArrayList<Long>();
		ids.add(consumeRecord.getId());
		accountingRelationsDao.deleteByConsumeCountIds(ids);
		this.saveAccountingRelations(consumeRecord, strConsumeUserIds);
	}

	@Transactional
	@Override
	public void deleteAccountingRelationsByConsumeRecordIds(List<Long> consumeRecordIds) {
		accountingRelationsDao.deleteByConsumeCountIds(consumeRecordIds);
		
	}

	@Override
	public List<Map<String, Object>> getAccountingRelationsList(Map<String, Object> optionMap) {
		List<Combo> userComboList = userService.getUserComboList(0);
		if(CollectionUtils.isNotEmpty(userComboList)){
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			Map<String, Object> map = null;
			String strDate = null;
			if(null != optionMap){
				//格式：yyyy-MM
				strDate = (String) optionMap.get("strDate");
			}
			Date countDate = null;
			if(StringUtils.isNotBlank(strDate)){
				//添加月份的第一天，时间格式：yyyy-MM-dd
				strDate = strDate + "-01";
				countDate = DateUtil.format(strDate, "yyyy-MM-dd");
			}else{
				countDate = new Date();
			}
			Calendar cal = Calendar.getInstance();
			cal.setTime(countDate);
			int year = cal.get(Calendar.YEAR);
			int month = cal.get(Calendar.MONTH) + 1;
			Map<String,Double> userSumMap = new HashMap<String,Double>();
			for (Combo sourceUser : userComboList) {
				map = new LinkedHashMap<String, Object>();
				map.put("sourceUser", sourceUser.getText());
				double totalSum = 0;
				for (int i = 0; i < userComboList.size(); i++) {
					double userSum = accountingRelationsDao.selectSumPayMoney(year, month, 
								Long.parseLong(sourceUser.getValue()), Long.parseLong(userComboList.get(i).getValue()));
					userSum = new BigDecimal(userSum).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
					totalSum += userSum;
					map.put("targetUser"+(i+1), userSum);	
					if(null == userSumMap.get("targetUser"+(i+1)))
						userSumMap.put("targetUser"+(i+1), userSum);
					else{
						userSum += userSumMap.get("targetUser"+(i+1));
						userSumMap.put("targetUser"+(i+1), userSum);
					}
				}
				map.put("totalSum", totalSum);
				list.add(map);
			}
			//合计
			map = new LinkedHashMap<String, Object>();
			map.put("sourceUser", "应收合计");
			double totalSum = 0;
			for (int i = 0; i < userComboList.size(); i++)  {
				totalSum += userSumMap.get("targetUser"+(i+1));
				map.put("targetUser"+(i+1), userSumMap.get("targetUser"+(i+1)));	
			}
			map.put("totalSum", new BigDecimal(totalSum).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			list.add(map);
			return list;
		}
		return null;
	}

	@Override
	public List<EasyuiDataGridColumns> getAccountingRelationsDataGridColumnList() {
		List<Combo> userComboList = userService.getUserComboList(0);
		if(CollectionUtils.isNotEmpty(userComboList)){
			List<EasyuiDataGridColumns> columns = new ArrayList<EasyuiDataGridColumns>(userComboList.size());
			EasyuiDataGridColumns column = new EasyuiDataGridColumns();
			column.setField("sourceUser");
			column.setTitle("用户名");
			columns.add(column);
			for (int i = 0; i < userComboList.size(); i++) {
				column = new EasyuiDataGridColumns();
				column.setField("targetUser"+(i+1));
				column.setTitle(userComboList.get(i).getText());
				columns.add(column);
			}
			column = new EasyuiDataGridColumns();
			column.setField("totalSum");
			column.setTitle("应付合计");
			columns.add(column);
			return columns;
		}
		return null;
	}

    @Override
    public String getByConsumeRecordId(Long consumeRecordId) {
        List<AccountingRelationsEntity> list = accountingRelationsDao.findByParam("consumeRecordId", consumeRecordId, "sourceUserId", null);
        if(CollectionUtils.isNotEmpty(list)){
            List<String> result = new ArrayList<String>(list.size());
            UserVo user = null;
            String userName = "";
            for (AccountingRelationsEntity accountingRelationsEntity : list) {
                user = userService.getUserByUserId(accountingRelationsEntity.getSourceUserId());
                userName = user == null ? "none" : user.getUserName();
                result.add(userName + "("+accountingRelationsEntity.getPayMoney()+")");
            }
            return StringUtils.join(result, ",");
        }
        return null;
    }
}
